package cn.com.zero.manager.auth.controller;

import cn.com.zero.base.exception.ErrorCodeException;
import cn.com.zero.manager.auth.mapper.ITestMapper;
import cn.com.zero.manager.auth.po.MenuPO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author Yang Yao
 * @version 1.0.0
 * @Description
 * @createTime 2023/3/8 10:42
 */
@RestController
@Transactional(rollbackFor = Throwable.class)
@RequestMapping("/manager")
public class TestController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ITestMapper testMapper;

    @ApiOperation(value = "添加权限")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "menuId", value = "菜单id"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "菜单名称"),
            @ApiImplicitParam(paramType = "query", name = "parentId", value = "父级菜单ID"),
            @ApiImplicitParam(paramType = "query", name = "url", value = "权限路径，其中 * 作为通配符"),
            @ApiImplicitParam(paramType = "query", name = "type", value = "菜单类型（1菜单  2功能）"),
            @ApiImplicitParam(paramType = "query", name = "sort", value = "排序"),
            @ApiImplicitParam(paramType = "query", name = "role", value = "角色编号")
    })
    @PostMapping("/addMenu")
    public void addMenu(
            @RequestParam("menuId") Long menuId,
            @RequestParam("name") String name,
            @RequestParam(value = "parentId", required = false) Long parentId,
            @RequestParam(value = "url", required = false) String url,
            @RequestParam("type") Integer type,
            @RequestParam("sort") Long sort,
            @RequestParam("role") String role) {
        MenuPO menuPO = testMapper.getMenuByMenuId(menuId);
        Optional<MenuPO> optional = Optional.ofNullable(menuPO);
        if (optional.isPresent()) {
            throw new ErrorCodeException(-100005L);
        }
        menuPO = testMapper.getMenuBySort(sort);
        Long maxSort = testMapper.getMaxSort();
        optional = Optional.ofNullable(menuPO);
        if (optional.isPresent()) {
            log.info("排序号已重复，目前的最大值为：{}", maxSort);
            throw new ErrorCodeException(-100004L, new String[]{String.valueOf(maxSort)}, "排序号已重复，目前的最大值为：%s");
        }
        testMapper.addMenu(menuId, name, parentId, url, type, sort);
        testMapper.addMenuAndRole(menuId, role);
    }
}
